﻿
CREATE PROCEDURE [dbo].[CashRegisterLinesUpdate]
(
	@PartyId int,
	@Qntty int,
	@RetailSum decimal(19, 2),
	@DiscountValue tinyint, --значение скидки по строке чека
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intDocTypeId int, @orgPartyId int, @orgDocId int, @orgQntty int, @datDocDate datetime
DECLARE @intInputCount int, @intOutputCount int
DECLARE @strBarCode char(12), @bitBlocked bit, @decPartyPrice decimal(19, 2), @intSaleDiscountTypesId int --тип скидки

	SET NOCOUNT ON
IF (@PartyId Is Null) OR (@Qntty Is Null) OR (@RetailSum Is Null)
OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Количество и сумма д.б. больше нуля !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgPartyId = PartyId, @orgDocId = DocId, @orgQntty = Qntty
FROM CA.GoodsDocLines WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId, @datDocDate = DocDate, @intSaleDiscountTypesId = ShiftDepartmentId 
FROM [CA].[Documents] WHERE Id = @orgDocId
IF (@intDocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Не найден документ с идентификатором ' + cast(@orgDocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 3) 
BEGIN
	SELECT @intErrCode = 5, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@orgDocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
SELECT @Qntty = @Qntty * (-1), @RetailSum = @RetailSum * (-1.0)

SELECT @strBarCode = BarCode, @bitBlocked = Blocked, @decPartyPrice = RetailPrice 
FROM CD.Parties WHERE Id = @PartyId

IF @PartyId <> @orgPartyId
BEGIN --другая партия

	IF EXISTS (SELECT TOP 1 Id FROM CA.GoodsDocLines WHERE ReturnLineId = @Original_Id )
	BEGIN
		SELECT @intErrCode = 6, 
		@strMsg = 'По строке чека с идентификатором ' + cast(@Original_Id as varchar(20)) + ' существуют возвраты!'
		RAISERROR (@strMsg, 11, @intErrCode)
		RETURN @intErrCode
	END
	
	IF @bitBlocked = 1
	BEGIN
		SELECT @intErrCode = 7, 
		@strMsg = 'Партия ' + @strBarCode + '(' + cast(@PartyId as varchar(20)) + ') заблокирована для продажи!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

	EXEC @intRet = dbo.CheckPartyFlow @PartyId, @Qntty, @datDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
	IF @intRet <> 0 RETURN @intRet

END ELSE BEGIN --партия не изменилась
	IF @orgQntty <> @Qntty --изменилось количество
	BEGIN

		IF @bitBlocked = 1
		BEGIN
			SELECT @intErrCode = 7, 
			@strMsg = 'Партия ' + @strBarCode + '(' + cast(@PartyId as varchar(20)) + ') заблокирована для продажи!'
			RAISERROR (@strMsg, 11, 1)
			RETURN @intErrCode
		END

		IF EXISTS (SELECT TOP 1 Id FROM CA.GoodsDocLines WHERE ReturnLineId = @Original_Id )
		BEGIN
			SELECT @intErrCode = 6, 
			@strMsg = 'По строке чека с идентификатором ' + cast(@Original_Id as varchar(20)) + ' существуют возвраты!'
			RAISERROR (@strMsg, 11, @intErrCode)
			RETURN @intErrCode
		END

		SET @intRet = @Qntty - @orgQntty
		IF @intRet < 0
		BEGIN
			EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @intRet, @datDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
			IF @intRet <> 0 RETURN @intRet
		END	
	END --OFF IF @orgQntty <> @Qntty
END --OFF IF @PartyId <> @orgPartyId

IF (@DiscountValue Is Not Null) AND (@intSaleDiscountTypesId Is Null) 
BEGIN
	SELECT @intErrCode = 8, 
	@strMsg = 'Чек создан без указания типа скидки!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @decPartyPrice = @decPartyPrice * (100.0 - IsNull(@DiscountValue, 0) ) * @Qntty / 100.0  --сумма со скидкой
IF @decPartyPrice <> @RetailSum
BEGIN
	SELECT @intErrCode = 8, 
	@strMsg = 'Неправильная сумма по строке чека!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC @intRet = dbo.CheckAllowUpdateDeleteForRecord @Original_Id
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
UPDATE [CA].[GoodsDocLines] SET 
[PartyId] = @PartyId, [Qntty] = @Qntty, [RetailSum] = @RetailSum, DiscountValue = @DiscountValue,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id AND MD = @Original_MD;

SELECT Id, DepartmentId, DocId, PartyId, 
Qntty * (-1) AS Qntty, 
RetailSum * (-1.0) AS RetailSum, DiscountValue,
Note, MD, MW 
FROM CA.GoodsDocLines
WHERE Id = @Original_Id

RETURN 0
